<template>

<div>

          <div>
            <!--搜索框-->
            <el-input
              style= "width: 250px"
              placeholder= "请输入角色ID搜索"
              suffix-icon= "el-icon-user"
              class= "ml-5"
              v-model= "roleId"
            ></el-input>
            <el-input
              style= "width: 250px"
              placeholder= "请输入角色名搜索"
              suffix-icon= "el-icon-chat-round"
              class= "ml-5"
              v-model= "roleName"
            ></el-input>
            <el-input
              style= "width: 250px"
              placeholder= "请输入角色描述搜索"
              suffix-icon= "el-icon-message"
              class= "ml-5"
              v-model= "des"
            ></el-input>
            <el-button class= "ml-5" type= "primary" plain @click= "load"
              ><b>搜索(支持模糊查询)</b></el-button
            >
            <el-button class= "ml-5" type= "info" plain @click= "clear"
              ><b>重置</b></el-button
            >
          </div>
          <div style= "margin: 10px 0">
            <el-button type= "primary" @click= "addHandler"
              >新增
              <i class= "el-icon-circle-plus-outline"></i>
            </el-button>
            <el-dialog title= "角色信息" :visible.sync= "addDialogFormVisible" width= "30%">
          <el-form>
            <el-form-item label= "角色ID">
              <el-input v-model= "form.roleId"
              autocomplete= "off"
              aria-required= "true"></el-input>
            </el-form-item>
            <el-form-item label= "角色名">
              <el-input
                v-model= "form.roleName"
                autocomplete= "off"
                aria-required= "true"
              ></el-input>
            </el-form-item>
            <el-form-item label= "角色描述">
              <el-input
                v-model= "form.des"
                autocomplete= "off"
                aria-required= "true"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot= "footer" class= "dialog-footer">
            <el-button @click= "addDialogFormVisible = false"> 取 消</el-button>
            <el-button type= "primary" @click= "save"> 确 定</el-button>
          </div>
        </el-dialog>
        <el-popconfirm
                  confirm-button-text= "好的"
                  cancel-button-text= "不用了"
                  icon= "el-icon-info"
                  icon-color= "red"
                  title= "您确定批量删除吗？"
                  @confirm= "batchDeleteHandler">
            <el-button type= "danger" slot = "reference" style= "margin-left:10px">
              批量删除
            <i class= "el-icon-delete"></i>
            </el-button>
          </el-popconfirm>
          </div>
          <el-table
            :data= "tableData"
            border
            stripe
            header-cell-class-name= "headerBg"
            @selection-change ="batchDelete"
            ><!--表格边框+斑马线-->
            <!--header-cell可以改变表头颜色，header-row-class-name不可以-->
                <el-table-column type= "selection" width= "55" >
                </el-table-column>
            <el-table-column prop= "roleId" label= "角色ID" width= "300"> </el-table-column>
            <el-table-column prop= "roleName" label= "角色名" width= "300">
            </el-table-column>
            <el-table-column prop= "des" label= "角色描述" width= "300">
            </el-table-column>
            <el-table-column label= "操作">
              <template slot-scope= "scope">
                <el-button type= "warning" @click= "editHandler(scope.row)">
                  编辑<i class= "el-icon-edit-outline"></i>
                </el-button>
                <el-dialog title= "编辑角色" :visible.sync= "editDialogFormVisible" width= "30%">
          <el-form>
            <el-form-item label= "角色ID">
              <el-input v-model= "form.roleId"
              autocomplete= "off"
              aria-required= "true" ></el-input>
            </el-form-item>
            <el-form-item label= "角色名">
              <el-input
                v-model= "form.roleName"
                autocomplete= "off"
                aria-required= "true"
              ></el-input>
            </el-form-item>
        <el-form-item label= "角色描述">
              <el-input
                v-model= "form.des"
                autocomplete= "off"
                aria-required= "true"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot= "footer" class= "dialog-footer">
            <!-- <el-button type= "primary" @click= "update"> 编辑</el-button> -->
            <el-button type= "primary" @click= "update"> 确定</el-button>
            <el-button @click= "editDialogFormVisible = false"> 取 消</el-button>

          </div>
        </el-dialog>
                <el-popconfirm
                  confirm-button-text= "好的"
                  cancel-button-text= "不用了"
                  icon= "el-icon-info"
                  icon-color= "red"
                  title= "确定删除？"
                  @confirm= "deleteHandler(scope.row.roleId)">
                  <el-button type= "danger" slot = "reference" class= "ml-5">删除<i class= "el-icon-delete"></i></el-button>
                </el-popconfirm>
                <el-button type= "primary" @click= "loadAuthData(scope.row.roleId) " class= "ml-5">
                  权限分配<i class= "el-icon-menu"></i>
                </el-button>
                <el-dialog title= "编辑权限" :visible.sync= "authDialogFormVisible" width= "30%">
                    <el-tree
                        node-key= "authId"
                        :props= "props"
                        :data= "authData"
                        ref= "tree"
                        :default-expanded-keys= "expands"
                        :default-checked-keys= "checks"
                        show-checkbox
                        highlight-current
                        ><!--@check-change="handleCheckChange"-->
                    </el-tree>
          <div slot= "footer" class= "dialog-footer">
            <!-- <el-button type= "primary" @click= "update"> 编辑</el-button> -->
            <el-button type= "primary" @click= "endowAuth"> 确定</el-button>
            <el-button @click= "authDialogFormVisible = false"> 取 消</el-button>

          </div>
        </el-dialog>
              </template>
            </el-table-column>
          </el-table>
          <div style= "padding: 10px 0">
            <!--分页-->
            <el-pagination
              @size-change= "handleSizeChange"
              @current-change= "handleCurrentChange"
              :current-page= "pageNum"
              :page-sizes= "[5, 10, 15, 20]"
              :page-size= "pageSize"
              layout= "total, sizes, prev, pager, next, jumper"
              :total= "total"
            >
            </el-pagination>
          </div>

</div>
</template>
<script>
export default {
  name: "Role",
  data() {
    return {
      //模糊分页查询
      tableData: [], //删除王小虎的假数据，表格数据默认空数组
      total: 0, //总条数
      pageNum: 1, //第几页
      pageSize: 5, //每页几条数据
      roleId:null,
      roleName:'',
      des: "",
      createTime: "",
      updateTime: "",
      //Dialog对话框
      dialogFormVisible: false,
      editDialogFormVisible: false,
      addDialogFormVisible:false,
      authDialogFormVisible:false,
      //多选框
      form: {},
      multipleSelection: [],
      //表格样式
      headBg: "headBg",
      authData:[],
      props:{
                children:"children",
                label:"authName"
      },
      expands:[],
      checks:[],
      authId:null,
      // authData:{}

    };
  },
  created() {
    this.load();
  },
  methods: {
    /*分页功能实现，与后端数据联动 */
    //MyBatis使用fetch方法自己将前后端连接起来（跨域问题的解决方法之一是在后端配置CoresConfig类开放后端端口），
    load() {
      //MyBatis-plus的时候我们使用axios将前后端数据联动
      //先安装axios，然后直接用就行
      this.request
        .get("http://localhost:8081/role/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            roleId: this.roleId,
            roleName: this.roleName,
            createTime: this.createTime,
            updateTime: this.updateTime,
          },
        })
        .then((res) => {
          console.log(res);

          this.tableData = res.data.records;
          this.total = res.data.total;
        });
    },
    loadAuthData(roleId){
      // console.log(this.roleId,this.$refs.tree.getCheckedKeys())
        this.authDialogFormVisible = true;
        this.roleId = roleId
        this.request.get("http://localhost:8081/authority").then((res)=>{
            this.authData = res.data;
            this.expands = res.data.map((v)=>v.authId)
        })

        this.request.get("http://localhost:8081/role/getAuth/"+ roleId).then((res)=>{
        this.checks = res.data
      })
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.pageNum = pageNum;
      this.load();
    },
    //模糊查询重置按钮方法
    clear() {
      this.roleId = null;
      this.roleName = "";
      this.des = "";
      this.load();
    },

    //(和对话框一起使用，点击按钮触发对话框，填写信息之后确定按钮进行最终操作)
    //编辑按钮实现
    editHandler(row) {
      //先将row的数据赋值给form，然后打开弹窗
      this.form = row;
      this.editDialogFormVisible = true;
    },
    addHandler() {
      this.addDialogFormVisible = true;
      this.form = {};
    },
    //后续操作（确定/取消按钮--->保存表单信息，删除表单信息，导入记录，导出记录）

    save() {
      //插入或者更新，后端写在了一起，所以这里也可以写在一起
      this.request
        .post("http://localhost:8081/role/save", this.form)
        .then((res) => {
          if (res.flag=='200') {
            this.$message.success("保存成功");
            this.addDialogFormVisible = false;
            this.load();
          } else {
            this.$message.error(res.msg);
            this.addDialogFormVisible = false;
          }
        });
    },
        update() {
      this.request
        .post("http://localhost:8081/role/update", this.form)
        .then((res) => {
          if (res.flag=='200') {
            this.$message.success("保存成功");
            this.editDialogFormVisible = false;
            this.load();
          } else {
            this.$message.error(res.msg);
            this.editDialogFormVisible = false;
          }
        });
    },
    //批量删除+普通单个删除
    batchDelete(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    batchDeleteHandler() {
      let roleIds = this.multipleSelection.map((v) => v.roleId); //将对象数组转化为id数组

      this.request
        .post("/role/batchDelete", roleIds)
        // .then((ids) => {
        //   if (ids == []) {
        //     this.$message.error("请先勾选要批量删除的记录!");
        //   }
        // })
        .then((res) => {
          if (res.flag == '200') {
            this.$message.success(res.msg);
            this.load();
          } else {
            this.$message.error(res.msg);
            this.dialogFormVisible = false;
          }
        });
    },

    deleteHandler(roleId) {
      this.request.delete("/role/" + roleId).then((res) => {
        if (res.flag == '200') {
          this.$message.success(res.msg);
          this.load();
        } else {
          this.$message.error(res.msg);
          this.dialogFormVisible = false;
        }
      });
    },
    endowAuth(){
          let result = this.$refs.tree.getCheckedKeys();
          console.log(result)
          this.request.post("http://localhost:8081/role/endowAuth/"+this.roleId,this.$refs.tree.getCheckedKeys()).then((res)=>{
              console.log(res)
              if(res.flag=='200'){
                this.$message.success("权限赋予成功！")
                this.authDialogFormVisible = false
              }else{
                  this.$message.error(res.msg);
                  this.authDialogFormVisible = false;
              }
          })

          console.log(this.$refs.tree)
    }
  }
};
</script>
<style>
.headerBg {
  background: #eee !important;
}
</style>